<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="120px">
      <el-form-item label="品牌" prop="brandType">
        <el-select v-model="queryParams.brandType" placeholder="请选择品牌" clearable>
          <el-option v-for="dict in device_brand" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="设备类型" prop="deviceType">
        <el-select v-model="queryParams.deviceType" placeholder="请选择设备类型" clearable>
          <el-option v-for="dict in device_type" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="设备型号" prop="deviceModel">
        <el-input v-model="queryParams.deviceModel" placeholder="请输入设备型号" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd"
          v-hasPermi="['service:deviceModel:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate"
          v-hasPermi="['service:deviceModel:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['service:deviceModel:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="Download" @click="handleExport"
          v-hasPermi="['service:deviceModel:export']">导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="deviceModelList" @selection-change="handleSelectionChange"
      @row-dblclick="handleRowDbClick" ref="tableRef">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" align="center" prop="id" />
      <el-table-column label="品牌" align="center" prop="brandType">
        <template #default="scope">
          <dict-tag :options="device_brand" :value="scope.row.brandType" />
        </template>
      </el-table-column>
      <el-table-column label="设备类型" align="center" prop="deviceType">
        <template #default="scope">
          <dict-tag :options="device_type" :value="scope.row.deviceType" />
        </template>
      </el-table-column>
      <el-table-column label="设备型号" align="center" prop="deviceModel" />
      <el-table-column label="回收配箱" align="center" prop="returnBoxCount" />
      <el-table-column label="废钞配箱" align="center" prop="wasteBoxCount" />
      <el-table-column label="配箱上限" align="center" prop="boxUpperCount" />
      <el-table-column label="钞箱容量(百万元)" align="center" prop="boxCapacity" />
    </el-table>

    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize"
      @pagination="getList" small layout="total, sizes, prev, pager, next, jumper" />

    <!-- 添加或修改设备型号对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body draggable>
      <el-form ref="deviceModelRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="品牌" prop="brandType">
          <el-select v-model="form.brandType" placeholder="请选择品牌">
            <el-option v-for="dict in device_brand" :key="dict.value" :label="dict.label"
              :value="parseInt(dict.value)"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="设备类型" prop="deviceType">
          <el-select v-model="form.deviceType" placeholder="请选择设备类型">
            <el-option v-for="dict in device_type" :key="dict.value" :label="dict.label"
              :value="parseInt(dict.value)"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="设备型号" prop="deviceModel">
          <el-input v-model="form.deviceModel" placeholder="请输入设备型号" />
        </el-form-item>
        <el-form-item label="回收配箱" prop="returnBoxCount">
          <el-input v-model="form.returnBoxCount" placeholder="请输入回收配箱" />
        </el-form-item>
        <el-form-item label="废钞配箱" prop="wasteBoxCount">
          <el-input v-model="form.wasteBoxCount" placeholder="请输入废钞配箱" />
        </el-form-item>
        <el-form-item label="配箱上限" prop="boxUpperCount">
          <el-input v-model="form.boxUpperCount" placeholder="请输入配箱上限" />
        </el-form-item>
        <el-form-item label="钞箱容量(百万元)" prop="boxCapacity">
          <el-input v-model="form.boxCapacity" placeholder="请输入钞箱容量(百万元)" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="DeviceModel">
import { ref, reactive, watch } from 'vue'
import { listDeviceModel, getDeviceModel, delDeviceModel, addDeviceModel, updateDeviceModel } from "@/api/service/deviceModel"
import { handleSingleSelection, handleSelectionHighlight } from "@/api/common"
import { number } from 'echarts'

const props = defineProps({
  // 用来指明组件是单独页面，还是独立组件
  isModal: {
    type: Boolean,
    default: true
  },
  // 用来关联父组件的modelValue/v-model属性
  modelValue: {
    type: Boolean,
    default: false
  },
  center: {
    type: Boolean,
    default: true
  },
  // 用来关联父组件的modelId属性
  modelId: {
    type: Number,
    default: null
  }
})

const emit = defineEmits(['select'])

// 添加一个计算属性用于监听组件可见性
// const visible = computed(() => {
//   // 当组件作为模态框使用时，通过open属性判断可见性
//   // 当组件作为内联组件使用时(isModal=false)，始终认为是可见的
//   return !props.isModal || open.value;
// });
const visible = computed({
  get() {
    return props.modelValue
  },
  set(value) {
    emit('update:modelValue', value)
  }
})

// 监听visible变化，当对话框打开时加载数据
watch(visible, (newVal) => {
  console.log('visible changed:', newVal);
  if (newVal) {
    getList();
    // 父页面传入的modelId，则根据ID查找并设置为当前选中项
    if (props.modelId) {
      const selectedModel = deviceModelList.value.find(item => item.id === props.modelId);
      if (selectedModel) {
        currentSelected.value = selectedModel;
      }
    }
  } else {
    // 关闭时重置选择
    currentSelected.value = {};
  }
});

const { proxy } = getCurrentInstance()
const { device_brand, device_type } = proxy.useDict('device_brand', 'device_type')

const deviceModelList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")
// 当前选中项
const currentSelected = ref({})
const tableRef = ref(null)

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    brandType: null,
    deviceType: null,
    deviceModel: null,
    returnBoxCount: null,
    wasteBoxCount: null,
    boxUpperCount: null,
    boxCapacity: null,
  },
  rules: {
    brandType: [
      { required: true, message: "品牌不能为空", trigger: "change" }
    ],
    deviceType: [
      { required: true, message: "设备类型不能为空", trigger: "change" }
    ],
    deviceModel: [
      { required: true, message: "设备型号不能为空", trigger: "blur" }
    ],
    returnBoxCount: [
      { required: true, message: "回收配箱不能为空", trigger: "blur" }
    ],
    wasteBoxCount: [
      { required: true, message: "废钞配箱不能为空", trigger: "blur" }
    ],
    boxUpperCount: [
      { required: true, message: "配箱上限不能为空", trigger: "blur" }
    ],
    boxCapacity: [
      { required: true, message: "钞箱容量(百万元)不能为空", trigger: "blur" }
    ],
  }
})

const { queryParams, form, rules } = toRefs(data)

/** 查询设备型号列表 */
function getList() {
  console.log("getList called");
  loading.value = true
  listDeviceModel(queryParams.value).then(response => {
    deviceModelList.value = response.rows
    total.value = response.total
    loading.value = false
    console.log("getList response, rows:", response.rows.length);
    // 父页面传入的modelId，则根据ID查找并设置为当前选中项
    if (props.modelId) {
      const deviceModel = deviceModelList.value.find(item => item.id === props.modelId)
      if (deviceModel) {
        currentSelected.value = deviceModel
      }
    }
    else {
      // 如果没有传入的modelId，则将当前选中项设置为空对象
      currentSelected.value = {}
    }
    // 数据更新后也要检查是否需要选中某行
    handleSelectionHighlight(tableRef, deviceModelList.value, currentSelected.value)
  }).catch(error => {
    loading.value = false;
  })
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    brandType: null,
    deviceType: null,
    deviceModel: null,
    returnBoxCount: null,
    wasteBoxCount: null,
    boxUpperCount: null,
    boxCapacity: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null,
    remark: null
  }
  proxy.resetForm("deviceModelRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据（实现单选行为）
function handleSelectionChange(selection) {
  // 使用通用函数处理单选逻辑
  const result = handleSingleSelection(selection, tableRef.value);

  ids.value = result.selectedItems;
  single.value = !result.isSingle;
  multiple.value = result.isEmpty;
  currentSelected.value = result.selectedItem;
}

// 双击行事件
function handleRowDbClick(row) {
  currentSelected.value = row
  if (!props.isModal) {
    emit('select', row)
    // 通过事件通知父组件关闭对话框
  }
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加设备型号"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _id = row.id || ids.value
  getDeviceModel(_id).then(response => {
    form.value = response.data
    open.value = true
    title.value = "修改设备型号"
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["deviceModelRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateDeviceModel(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addDeviceModel(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value
  proxy.$modal.confirm('是否确认删除设备型号编号为"' + _ids + '"的数据项？').then(function () {
    return delDeviceModel(_ids)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => { })
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('service/deviceModel/export', {
    ...queryParams.value
  }, `deviceModel_${new Date().getTime()}.xlsx`)
}

// 确认选择
function handleSelectConfirm() {
  if (Object.keys(currentSelected.value).length > 0) {
    emit('select', currentSelected.value)
  } else {
    // 如果没有选中任何项，显示提示信息
    proxy.$modal.msgWarning("请先选择一条数据")
  }
}

getList()

// 向外暴露方法
defineExpose({
  handleSelectConfirm,
  currentSelected
})
</script>
<style scoped>
:deep(.el-input),
:deep(.el-select .el-input) {
  width: 215px;
  box-sizing: border-box;
}
</style>